package com.example.confirm_retrun;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Objects;

/**
 * @BelongsProject: RabbitMqLearn
 * @BelongsPackage: com.wang.config
 * @Author: wang fei
 * @CreateTime: 2023-02-04  17:30
 * @Description: TODO
 * @Version: 1.0
 */
@Component
public class RabbitConfirmConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * @description: 注⼊当前监听器到RabbitTemplate
     * @method: init
     * @author: wang fei
     * @date: 2023/2/6 17:45:56
     **/
    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        String dataId = "";
        if (Objects.nonNull(correlationData)) {
            dataId = correlationData.getId();
        }
        if (b) {
            //信息发送成功
            System.out.printf("消息发送成功:" + dataId);
        } else {
            //信息发送失败
            System.out.printf("消息发送失败:" + s);
        }
    }

    /**
     * @description: 当消息没办法抵达队列时会被调⽤
     * @method: returnedMessage
     * @author: wang fei
     * @date: 2023/2/6 18:20:03
     * @param: [message, i, s, s1, s2]
     * @return: void
     **/
    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {
        System.out.println("消息：" + new String(message.getBody()) + "，没有投递到队列");
    }
}
